﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AvalonDock;
using OpenExpressApp.Module.WPF;
using OpenExpressApp.Module.Library.Security;
using System.Timers;
using Csla;
using OpenExpressApp.Module.Library;
using System.Diagnostics;
using System.Windows.Threading;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Windows.Controls.Primitives;
using OpenExpressApp.Library;
using System.Configuration;

namespace OpenExpressApp
{
    public class DocumentPaneWorkSpace : IWorkspace
    {
        public DocumentPane DocumentPane { get; set; }
        public DocumentPaneWorkSpace(DocumentPane dp)
        {
            DocumentPane = dp;
        }

        public void Add(IWindow window)
        {
            DocumentPane.Items.Add(new DocumentContent() { Content = window, Title = window.Title});
        }

        public void Active(IWindow window)
        {
            DocumentContent dc = GetDocumentContent(window.Title);
            if (dc != null) DocumentPane.SelectedItem = dc;
        }

        public void Remove(IWindow window)
        {
            DocumentContent dc = GetDocumentContent(window.Title);
            if (dc != null) DocumentPane.Items.Remove(dc);
        }

        public IWindow GetWindow(string title)
        {
            DocumentContent dc = GetDocumentContent(title);
            return dc != null? dc.Content as IWindow : null;
        }

        private DocumentContent GetDocumentContent(string title)
        {
            foreach (DocumentContent item in DocumentPane.Items)
            {
                if (item.Title == title)
                {
                    return item;
                }
            }
            return null;
        }
    }

    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    [Export(ContractName.MainWindow, typeof(Window))]
    public partial class Shell : Window, IPartImportsSatisfiedNotification
    {
        [ImportMany(ContractName.Tools)]
        public IEnumerable<Control> Tools { get; set; }

        [Export(ContractName.Pads, typeof(ItemsControl))]
        public ItemsControl Pads
        {
            get
            {
                return Pads;
            }
        }

        [Export(ContractName.Workspace, typeof(IWorkspace))]
        private DocumentPaneWorkSpace _Workspace
        {
            get
            { 
                return new DocumentPaneWorkSpace(workspace); 
            }
        }

        public void OnImportsSatisfied()
        {
            foreach (var item in Tools)
                this.tools.Items.Add(new DockableContent() { Content = item });
        }

        public Shell()
        {
            InitializeComponent();

            this.txtServer.Text = string.Format("服务器地址：{0}", AppConfig.Instance.RemoteServerAddress);
            themes.ItemsSource = OpenExpressApp.WPF.Themes.ThemeManager.GetThemes();
            string theme = ConfigurationManager.AppSettings["Theme"];
            if (string.IsNullOrEmpty(theme) == false)
            {
                themes.SelectedValue = theme;
            }

            this.txtUserName.Text = Csla.ApplicationContext.User.Identity.Name;
            sdScale.Value = AppConfig.Instance.ZoomScale;
            sdScale.ValueChanged += sdScale_ValueChanged;
            this.LoginTime();
        }

        private void btnModifyPwd_Click(object sender, RoutedEventArgs e)
        {
            ModifyUserPasswordDialog.Execute((Csla.ApplicationContext.User.Identity as OEAIdentity).User);
        }

        private void btnHelp_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("http://openexpressapp.codeplex.com/");
        }

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutFrm about = new AboutFrm(this);
            about.ShowDialog();
        }

        private void sdScale_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            (sender as Slider).Value = 1.0;
        }

        #region 限制用户使用时间

        private static readonly int TICK_INTERVEL = 60 * 1000;// 1Minutes

        private Timer _timer = new Timer();

        private TimeSpan _availableTime;

        /// <summary>
        /// 限制用户的使用时间。
        /// </summary>
        private void LoginTime()
        {
            var currentUser = (ApplicationContext.User.Identity as OEAIdentity).User;
            this._availableTime = User.GetAvailableTime(currentUser);
            if (this._availableTime.Ticks > 0)
            {
                this._timer.Interval = TICK_INTERVEL;
                this._timer.Elapsed += (o, e) =>
                {
                    this._availableTime -= new TimeSpan(TICK_INTERVEL);
                    if (this._availableTime.Ticks <= 0)
                    {
                        this._timer.Stop();
                        MessageBox.Show("每次使用时间已到！程序退出！");
                        this.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
                    }
                };
                this._timer.Start();
            }
        }

        #endregion

        private void sdScale_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            AppConfig.Instance.ZoomScale = sdScale.Value;
            AppConfig.Instance.Save();
        }
    }
}